#include "MySqlTableModel.h"
#include <QPushButton>
#include <QDebug>

MySqlTableModel::MySqlTableModel(QObject *parent)
    : QSqlTableModel(parent)
{
    Q_UNUSED(parent);
//    connect(this, SIGNAL(stateChanged(int)), this, SLOT(onStateChanged(int)));
}

bool MySqlTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if(!index.isValid())
        return false;
    if (role == Qt::CheckStateRole && index.column() == checkColumn){
        emit dataChanged(index,index);
        check_state_map[index.row()] = (value == Qt::Checked ? Qt::Checked : Qt::Unchecked);
        qDebug() << (value == Qt::Checked);
//        onStateChanged();//判断表头复选框处于什么状态
        return true;
    }
    else
    {
        emit dataChanged(index,index);//通知窗口数据变化，更新窗口
        return QSqlTableModel::setData(index, value,role);
    }
    return QSqlTableModel::setData(index, value,role);
}
QVariant MySqlTableModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) return QVariant();

    switch(role)
    {
        case Qt::TextAlignmentRole:
            return Qt::AlignCenter;
        case Qt::CheckStateRole:
            if (index.column() != checkColumn){
                return QSqlTableModel::data(index, role);
            }
            if(index.column() == checkColumn){
                if (check_state_map.contains(index.row())){
                    return check_state_map[index.row()] == Qt::Checked ? Qt::Checked : Qt::Unchecked;

                }
                return Qt::Unchecked;
            }
        default:
            return QSqlTableModel::data(index, role);
    }
    return QVariant();
}
Qt::ItemFlags MySqlTableModel::flags(
    const QModelIndex &index) const //返回表格是否可更改的标志
{
    if (!index.isValid()) return nullptr;
    if (index.column() == checkColumn)
        return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable|Qt::ItemIsEditable;//设置第一列为可改
    else
        return QSqlTableModel::flags(index);
    return  Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}


////更新表头按钮状态
//void MySqlTableModel::onStateChanged()
//{
//    int check=0,uncheck=0;
//    foreach(int i,check_state_map.keys())
//    {
//        if(check_state_map.value(i) == Qt::Checked)
//            check++;
//        else
//            uncheck++;
//    }
//    if(check==rowCount())
//        emit stateChanged(Qt::Checked);
//    else if (uncheck==check_state_map.keys().count())
//        emit stateChanged(Qt::Unchecked);
//    else
//        emit stateChanged(Qt::PartiallyChecked);
//}
////更新复选框状态
//void MySqlTableModel::onStateChanged(int state)
//{
////    qDebug() << "THERE" << state;
//    state == Qt::Checked?Qt::Checked:Qt::Unchecked;//判断全选是选中还是未选中
//    QModelIndex index;
//    for (int i = 0; i < rowCount(); ++i)
//    {
//        index = this->index(i, 0);
//        setData(index, state, Qt::CheckStateRole);//使用自己重写的setData更新状态
//    }
//}
